import React, { useState, useEffect } from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import {
  Toolbar,
  Hidden,
  List,
  ListItem,
  ListItemIcon,
  Popover,
  Typography,
  IconButton,
  Button,
  Avatar
} from '@material-ui/core';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import MenuIcon from '@material-ui/icons/Menu';
import { Image, DarkModeToggler } from 'components/atoms';
import logoIcon from 'assets/images/crowded_logo_h.png';
import { useSelector } from 'react-redux'

const useStyles = makeStyles(theme => ({
  flexGrow: {
    flexGrow: 1,
  },
  navigationContainer: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  toolbar: {
    maxWidth: theme.layout.contentWidth,
    width: '100%',
    margin: '0 auto',
    padding: theme.spacing(0, 2),
    [theme.breakpoints.up('sm')]: {
      padding: theme.spacing(0, 8),
    },
    backgroundColor: theme.palette.alternate.main
  },
  navLink: {
    '&:hover': {
      color: theme.palette.primary.dark,
    },
  },
  listItem: {
    cursor: 'pointer',
    '&:hover > .menu-item, &:hover svg': {
      color: theme.palette.primary.dark,
    },
    '&.menu-item--no-dropdown': {
      paddingRight: 0,
    },
  },
  listItemActive: {
    '&> .menu-item': {
      color: theme.palette.primary.dark,
    },
  },
  listItemText: {
    flex: '0 0 auto',
    marginRight: theme.spacing(2),
    whiteSpace: 'nowrap',
  },
  listItemButton: {
    whiteSpace: 'nowrap',
  },
  listItemIcon: {
    minWidth: 'auto',
  },
  popover: {
    padding: theme.spacing(2),
    border: theme.spacing(2),
    boxShadow: '0 0.5rem 2rem 2px rgba(116, 123, 144, 0.09)',
    minWidth: 200,
    marginTop: theme.spacing(2),
  },
  iconButton: {
    marginLeft: theme.spacing(2),
    padding: 0,
    '&:hover': {
      background: 'transparent',
    },
  },
  expandOpen: {
    transform: 'rotate(180deg)',
    color: theme.palette.primary.dark,
  },
  logoContainer: {
    width: 100,
    height: 28,
    [theme.breakpoints.up('md')]: {
      width: 120,
      height: 32,
    },
  },
  logoImage: {
    width: '197px',
    height: '40px',
  },
  menu: {
    display: 'flex',
    justifyContent: 'space-between',
  },
  menuItem: {
    marginRight: theme.spacing(1),
    '&:last-child': {
      marginRight: 0,
    },
  },
  menuGroupItem: {
    paddingTop: 0,
  },
  menuGroupTitle: {
    textTransform: 'uppercase',
  },
  avatarContainer: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  avatar: {
      marginRight: theme.spacing(1),
  },
}));

const Topbar = ({ onSidebarOpen, pages, className, ...rest }) => {
  const classes = useStyles();
  const profileData = useSelector((state) => state.auth.profileData)
  console.log('profileData', profileData)    

  const [anchorEl, setAnchorEl] = useState(null);
  const [openedPopoverId, setOpenedPopoverId] = useState(null);
  const [selectedItem, setSelectedItem] = useState({});

  useEffect(() => {
    selectedItem[pages.user_types.id] = pages.user_types.pages[0];
    selectedItem[pages.sort_by.id] = pages.sort_by.pages[0];
    setSelectedItem(selectedItem);
  }, [])

  const handleClick = (event, popoverId) => {
    console.log('handleClick', 'clicked');
    setAnchorEl(event.target);
    setOpenedPopoverId(popoverId);
  };

  const handleItem = (pageId, page) => {
    console.log('handleItem', 'clicked');
    selectedItem[pageId] = page;
    setSelectedItem(selectedItem);

    handleClose();
  };

  const handleClose = () => {
    setAnchorEl(null);
    setOpenedPopoverId(null);
  };

  const MenuGroup = props => {
    const { item } = props;
    return (
      <List disablePadding>
        {item.pages.map((page, i) => (
          <ListItem disableGutters key={i} className={classes.menuGroupItem}>
            <Button
              style={{textTransform: 'none'}}
              color={page == selectedItem[item.id] ? "primary" : "default"}
              onClick={e=>{
                e.stopPropagation()
                handleItem(item.id, page)}}
            >
              {page}
            </Button>
          </ListItem>
        ))}
      </List>
    );
  };

  const UserTypePages = () => {
    return (
      <div className={classes.menuItem}>
        <MenuGroup item={pages.user_types} />
      </div>
    );
  };

  const SortByPages = () => {
    return (
      <div className={classes.menuItem}>
        <MenuGroup item={pages.sort_by} />
      </div>
    );
  };

  const renderPages = id => {
    if (id === 'user_type') {
      return <UserTypePages />;
    } else if (id === 'sort_by') {
      return <SortByPages />;
    }
  };

  return (
    <Toolbar disableGutters className={classes.toolbar} {...rest}>
      <List disablePadding className={classes.navigationContainer}>
        {[pages.user_types, pages.sort_by].map((page, i) => (
          <div key={page.id}>
            <ListItem
                aria-describedby={page.id}
                onClick={e => {
                  e.stopPropagation()
                  handleClick(e, page.id)}}
                className={clsx(
                    classes.listItem,
                    openedPopoverId === page.id ? classes.listItemActive : '',
                )}
            >
              {page.title} : &nbsp;
                <Typography
                  variant="body1"
                  color="textPrimary"
                  className={clsx(classes.listItemText, 'menu-item')}
                >
                  {selectedItem[page.id]}
                </Typography>
                <ListItemIcon className={classes.listItemIcon}>
                    <ExpandMoreIcon
                        className={
                            openedPopoverId === page.id ? classes.expandOpen : ''
                        }
                        fontSize="small"
                    />
                </ListItemIcon>
            </ListItem>
            <Popover
                elevation={1}
                id={page.id}
                open={openedPopoverId === page.id}
                anchorEl={anchorEl}
                onClose={handleClose}
                anchorOrigin={{
                    vertical: 'bottom',
                    horizontal: 'center',
                }}
                transformOrigin={{
                    vertical: 'top',
                    horizontal: 'center',
                }}
                classes={{ paper: classes.popover }}
            >
                <div>{renderPages(page.id)}</div>
            </Popover>
          </div> 
        ))}
      </List>
    </Toolbar>
  );
};

Topbar.propTypes = {
  className: PropTypes.string,
  onSidebarOpen: PropTypes.func,
  pages: PropTypes.object.isRequired,
};

export default Topbar;
